<template>

    <fullscreenModal :modal="showAddrModal" :label="addEdit?'新增收货地址':'编辑收货地址'" :isShowEdit="false" :showSave="false" editType="rightClose" @handleClose="showAddrModal = false">
        <div class="addressEdit">
            <van-form ref="form" label-width="4.1em">
                <van-field v-model="formData.receiver" clearable required name="姓名" label="姓名" placeholder="收货人姓名" :error="false" :rules="ruleForm.receiver" />
                <van-field v-model="formData.receiverContact" clearable required name="电话" label="电话" placeholder="收货人手机号" :error="false" :rules="ruleForm.tel" />
                <van-field v-model="areaValue" required is-link name="地区" label="地区" placeholder="点击选择省/市/区" readonly :error="false" :rules="ruleForm.areaValue" @click="showArea = true" />
                <van-popup v-model="showArea" round position="bottom">
                    <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="dataList" @change="loadData" @close="show = false" @finish="onFinish" />
                </van-popup>

                <van-field v-model="formData.detailAddr" clearable required name="详细地址" label="详细地址" placeholder="请填写详细地址" :error="false" :rules="ruleForm.detailAddr" />
            </van-form>
            <van-cell class="defBox" title="设为默认收货地址">
                <template #right-icon>
                    <van-switch style="font-size: 24px;" v-model="formData.isDefault" />
                </template>
            </van-cell>
            <div class="btnBox">
                <van-button round type="info" block @click="onSubmit">保存</van-button>
                <van-button v-if="!addEdit" round block @click="onDelete">删除</van-button>
            </div>
        </div>
    </fullscreenModal>
</template>

<script>
    import { queryArea } from "@/api/common";
    import { addAddress, editAddress, delAddress } from '@api/platframe/mainFrame/address';

    export default {
        data () {
            return {
                showAddrModal: false,
                addEdit: true,
                areaValue: "", //所选地区
                cascaderValue: "",
                showArea: false, // 地区弹窗显示
                dataList: [],// 
                // 收货人信息初始值
                formData: {
                    addrId: "",  // 收货地址标识
                    cityCode: "",// 市编码
                    cityName: "",// 市名称
                    countyCode: "",// 县编码
                    countyName: "",// 县名称
                    detailAddr: "",// 详细地址
                    isDefault: false, // 是否默认 1：是 0：否
                    provCode: "", // 省编码
                    provName: "",// 省名称
                    receiver: "", // 收货人
                    receiverContact: "", // 收货人手机号
                    staffId: "", // 人员标识
                },
                // 必填项校验
                ruleForm: {
                    receiver: [
                        { required: true, message: "请填写收货人姓名", trigger: "onBlur" },
                    ],
                    tel: [
                        { required: true, message: "请填写收货人手机号", trigger: "onBlur" },
                        {
                            pattern: this.$commonReg.phoneReg,
                            message: this.$commonReg.phoneMsg,
                            trigger: "onBlur",
                        },
                    ],
                    areaValue: [
                        { required: true, message: "请选择地区", trigger: "blur" },
                    ],
                    detailAddr: [
                        { required: true, message: "请填写详细地址", trigger: "blur" },
                    ],
                },
            };
        },
        computed: {},
        methods: {
            // 获取地址树
            getInitTree () {
                queryArea("", "1").then((res) => {
                    if (res.code == "1000") {
                        let data = res.data;
                        data = this.operationTree(data);
                        this.dataList = data;
                    }
                });
            },
            // 处理地址树
            operationTree (arr) {
                let arrData = [];
                arr.forEach((item) => {
                    if (item.areaLevel > 2) {
                        arrData.push({
                            value: item.areaCode,
                            text: item.areaName,
                        });
                    } else {
                        arrData.push({
                            value: item.areaCode,
                            text: item.areaName,
                            level: item.areaLevel,
                            children: [],
                            // loading: false,
                        });
                    }
                });
                return arrData;
            },
            // 切换地区
            loadData (item) {
                item.loading = true;
                queryArea(item.value, Number(item.level) + 1).then((res) => {
                    item.loading = false;
                    if (res.code == "1000") {
                        let data = res.data;
                        data = this.operationTree(data);
                        if (item.tabIndex == 0) {
                            item.selectedOptions[0].children = data;
                        } else {
                            item.selectedOptions[1].children = data;
                        }
                    }
                });
            },
            // 全部选项选择完毕后，会触发 finish 事件
            onFinish (item) {
                this.showArea = false;
                this.areaValue = item.selectedOptions
                    .map((option) => option.text)
                    .join("/");
                this.formData.provCode = item.selectedOptions[0].value;
                this.formData.cityCode = item.selectedOptions[1].value;
                this.formData.countyCode = item.selectedOptions[2].value;
            },
            // 保存
            onSubmit () {
                // 全局表单验证
                this.$refs.form.validate().then(() => {
                    let arr = this.areaValue.split('/');
                    this.formData.provName = arr[0];
                    this.formData.cityName = arr[1];
                    this.formData.countyName = arr[2];
                    if (this.formData.isDefault) {
                        this.formData.isDefault = "1"
                    } else {
                        this.formData.isDefault = "0"
                    }

                    this.Interface();
                }).catch(() => {
                    // this.$toast.fail('请完成必填项！')
                })
            },
            // 走接口(新增/修改)
            async Interface () {
                let obj = { ...this.formData };

                let res = null;
                if (this.addEdit) {
                    res = await addAddress(obj);
                } else {
                    res = await editAddress(obj);
                }

                if (res && res.code === 1000) {
                    this.$Notify({ type: 'success', message: '保存成功！' });
                    this.$emit('refresh');
                    this.showAddrModal = false;
                }
            },
            // 删除
            async onDelete () {
                let obj = {
                    'addrIdList': this.formData.addrId
                };
                let res = await delAddress(obj);
                if (res && res.code === 1000) {
                    this.$Notify({ type: 'success', message: '删除成功！' });
                    this.$emit('refresh');
                    this.showAddrModal = false;
                }
            },
            getData (obj) {
                this.formData = {
                    addrId: "",  // 收货地址标识
                    cityCode: "",// 市编码
                    cityName: "",// 市名称
                    countyCode: "",// 县编码
                    countyName: "",// 县名称
                    detailAddr: "",// 详细地址
                    isDefault: false, // 是否默认 1：是 0：否
                    provCode: "", // 省编码
                    provName: "",// 省名称
                    receiver: "", // 收货人
                    receiverContact: "", // 收货人手机号
                    staffId: "", // 人员标识
                }
                this.areaValue = '';
                this.cascaderValue = '';
                setTimeout(() => {
                    this.$refs.form.resetValidation();
                    this.showAddrModal = true;
                    this.addEdit = obj.key === "add";
                    if (!this.addEdit) {
                        this.formData = obj.val;
                        this.areaValue = obj.val.provName + "/" + obj.val.cityName + "/" + obj.val.countyName;
                    }
                })
            }
        },
        mounted () {
            this.formData.staffId = sessionStorage.getItem("userid");
            this.getInitTree();
        }
    };
</script>

<style scoped lang="less">
    ::v-deep .van-nav-bar__left {
        i,
        .van-nav-bar__text {
            color: #000;
        }
    }
    ::v-deep .van-button--danger {
        background-color: #1989fa;
        border-color: #1989fa;
    }
    .addressEdit {
        padding: 12px;
        .van-form {
            div:nth-child(1) {
                border-top-left-radius: 10px;
                border-top-right-radius: 10px;
            }
            div:nth-child(4) {
                border-bottom-right-radius: 10px;
                border-bottom-left-radius: 10px;
            }
        }
        .fieldsBox {
            overflow: hidden;
            border-radius: 10px;
        }
        .defBox {
            margin-top: 12px;
            overflow: hidden;
            border-radius: 8px;
        }
        .btnBox {
            padding: 32px 0px;
            .van-button {
                margin-bottom: 12px;
            }
        }
    }
</style>